package com.centaline.androidsalesblog.activities.newest;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.percent.PercentRelativeLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.bumptech.glide.DrawableRequestBuilder;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.map.AroundMapActivity;
import com.centaline.androidsalesblog.activities.mine.LoginActivity;
import com.centaline.androidsalesblog.activities.news.ChatActivity;
import com.centaline.androidsalesblog.activities.sale.EsfEstateDetailActivity;
import com.centaline.androidsalesblog.api.newest.NewEstActListApi;
import com.centaline.androidsalesblog.api.newest.NewEstListApi;
import com.centaline.androidsalesblog.api.newest.NewPropExtInfoApi;
import com.centaline.androidsalesblog.api.newest.NewPropImgApi;
import com.centaline.androidsalesblog.api.newest.NewPropPhoneApi;
import com.centaline.androidsalesblog.api.newest.NewPropStaffApi;
import com.centaline.androidsalesblog.api.sale.EsfEstateListApi;
import com.centaline.androidsalesblog.application.MyLocation;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.AppNameType;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.constants.SourceType;
import com.centaline.androidsalesblog.constants.SprfConstant;
import com.centaline.androidsalesblog.events.MineInfoUpdate;
import com.centaline.androidsalesblog.iml.ImgViewPagerClickListener;
import com.centaline.androidsalesblog.iml.RecyclerViewItemOnClickListener;
import com.centaline.androidsalesblog.iml.StaffItemDetailOnClick;
import com.centaline.androidsalesblog.model.businissobject.BaseNewPropBo;
import com.centaline.androidsalesblog.model.businissobject.CollectInfoBo;
import com.centaline.androidsalesblog.model.businissobject.NewPropExtInfoBo;
import com.centaline.androidsalesblog.model.businissobject.NewPropImgBo;
import com.centaline.androidsalesblog.model.businissobject.NewPropPhoneBo;
import com.centaline.androidsalesblog.model.businissobject.NewPropStaffBo;
import com.centaline.androidsalesblog.model.businissobject.ShareBo;
import com.centaline.androidsalesblog.model.databaseobject.BizUnitDo;
import com.centaline.androidsalesblog.model.databaseobject.EsfEstateDo;
import com.centaline.androidsalesblog.model.databaseobject.NewEstActDo;
import com.centaline.androidsalesblog.model.databaseobject.NewEstDo;
import com.centaline.androidsalesblog.model.databaseobject.StaffDo;
import com.centaline.androidsalesblog.model.responseobject.CollectInfoListRo;
import com.centaline.androidsalesblog.model.responseobject.EsfEstateListRo;
import com.centaline.androidsalesblog.model.responseobject.NewEstActListRo;
import com.centaline.androidsalesblog.model.responseobject.NewEstListRo;
import com.centaline.androidsalesblog.model.responseobject.NewPropExtInfoRo;
import com.centaline.androidsalesblog.model.responseobject.NewPropImgRo;
import com.centaline.androidsalesblog.model.responseobject.NewPropPhoneRo;
import com.centaline.androidsalesblog.model.responseobject.NewPropStaffListRo;
import com.centaline.androidsalesblog.model.responseobject.SimpleUserCenterRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.rx.map.RxMap;
import com.centaline.androidsalesblog.rx.request.RxRequest;
import com.centaline.androidsalesblog.utils.BdMapUtil;
import com.centaline.androidsalesblog.utils.ContactUtil;
import com.centaline.androidsalesblog.utils.DateUtil;
import com.centaline.androidsalesblog.utils.PriceUtil;
import com.centaline.androidsalesblog.utils.RongUserIdUtil;
import com.centaline.androidsalesblog.utils.TextFormatUtil;
import com.centaline.androidsalesblog.widgets.CollectView;
import com.centaline.androidsalesblog.widgets.ConsultView;
import com.centaline.androidsalesblog.widgets.NewEstDetailImgLayout;
import com.centaline.androidsalesblog.widgets.NewEstHouseTypeView;
import com.centaline.androidsalesblog.widgets.ShareDialog;
import com.centaline.androidsalesblog.widgets.dropdown.SpecialLoadView;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.interfaces.IResponseListener;
import com.centanet.framework.utils.SprfUtil;
import com.centanet.framework.widget.AbstractSpecialLoadView;
import com.trello.rxlifecycle.ActivityEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Locale;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 新房详情
 */
public class NewEstDetailActivity extends BaseActivity implements View.OnClickListener {

    private NewEstDetailImgLayout newEstDetailImgLayout;
    private SpecialLoadView specialLoadView;
    private AppCompatTextView atv_price, atv_status, atv_open, atv_live, atv_feature, atv_fitment,
            atv_property_right, atv_mgt_price, atv_mgt_company, atv_developer, atv_address, atv_map_name,
            atv_traffic, atv_support, atv_nav, atv_share;
    private ImageView img_arrow_address, img_map, arrow_traffic, arrow_support;
    private ViewStub vs_house_type, vs_activity, vs_around_new_est, vs_around_esf, vs_new_est_traffic,
            vs_new_est_support;
    private RelativeLayout rl_map;
    private Button btn_consult;
    private View overView;
    private ConsultView consultView;
    private BottomSheetBehavior bottomSheetBehavior;
    private CollectView collectView;
    private PercentRelativeLayout prl_tool;

    private ArrayList<NewPropImgBo> newPropImgBos = new ArrayList<>();//大图
    private ArrayList<String> bigImgList = new ArrayList<>();//大图列表
    private ArrayList<NewPropImgBo> houseTypeImgBos = new ArrayList<>();//户型
    private ArrayList<String> houseTypeImgList = new ArrayList<>();//大图列表
    private ArrayList<NewEstActDo> newEstActDos = new ArrayList<>();//活动列表
    private ArrayList<NewEstDo> newEstDos = new ArrayList<>();//周边新盘
    private ArrayList<EsfEstateDo> esfEstateDos = new ArrayList<>();//周边小区
    private ArrayList<NewPropStaffBo> newPropStaffBos = new ArrayList<>();//新盘联系人
    private DrawableRequestBuilder<String> requestBuilder;
    private String newEstId;
    private NewPropExtInfoBo newPropExtInfoBo;
    private String newPropImg;
    private boolean saleEnable;//二手房是否可用
    private boolean expandTraffic, expandSupport;//交通、配套展开
    private NewPropPhoneApi newPropPhoneApi;
    private LocationClient locationClient;

    private String shareUrl;
    private ShareDialog shareDialog;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_new_est_detail;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar();
        newEstDetailImgLayout = (NewEstDetailImgLayout) findViewById(R.id.newEstDetailImgLayout);
        specialLoadView = (SpecialLoadView) findViewById(R.id.specialLoadView);
        atv_price = (AppCompatTextView) findViewById(R.id.atv_price);
        atv_status = (AppCompatTextView) findViewById(R.id.atv_status);
        atv_open = (AppCompatTextView) findViewById(R.id.atv_open);
        atv_live = (AppCompatTextView) findViewById(R.id.atv_live);
        atv_feature = (AppCompatTextView) findViewById(R.id.atv_feature);
        atv_fitment = (AppCompatTextView) findViewById(R.id.atv_fitment);
        atv_property_right = (AppCompatTextView) findViewById(R.id.atv_property_right);
        atv_mgt_price = (AppCompatTextView) findViewById(R.id.atv_mgt_price);
        atv_mgt_company = (AppCompatTextView) findViewById(R.id.atv_mgt_company);
        atv_developer = (AppCompatTextView) findViewById(R.id.atv_developer);
        vs_house_type = (ViewStub) findViewById(R.id.vs_house_type);
        vs_activity = (ViewStub) findViewById(R.id.vs_activity);
        vs_around_new_est = (ViewStub) findViewById(R.id.vs_around_new_est);
        vs_around_esf = (ViewStub) findViewById(R.id.vs_around_esf);
        atv_address = (AppCompatTextView) findViewById(R.id.atv_address);
        atv_map_name = (AppCompatTextView) findViewById(R.id.atv_map_name);
        atv_nav = (AppCompatTextView) findViewById(R.id.atv_nav);
        atv_share = (AppCompatTextView) findViewById(R.id.atv_share);
        rl_map = (RelativeLayout) findViewById(R.id.rl_map);
        img_arrow_address = (ImageView) findViewById(R.id.img_arrow_address);
        img_map = (ImageView) findViewById(R.id.img_map);
        vs_new_est_traffic = (ViewStub) findViewById(R.id.vs_new_est_traffic);
        vs_new_est_support = (ViewStub) findViewById(R.id.vs_new_est_support);
        btn_consult = (Button) findViewById(R.id.btn_consult);
        overView = findViewById(R.id.overView);
        consultView = (ConsultView) findViewById(R.id.consultView);
        collectView = (CollectView) findViewById(R.id.collectView);
        prl_tool = (PercentRelativeLayout) findViewById(R.id.prl_tool);
    }

    @Override
    protected void initViews() {
        requestBuilder = GlideLoad.init(this);
        newEstDetailImgLayout.setRequestBuilder(requestBuilder);
        newEstDetailImgLayout.setImgViewPagerClickListener(new ImgViewPagerClickListener() {
            @Override
            public void imgItemClick(int position) {
                startActivity(new Intent(NewEstDetailActivity.this, NewPropImgListActivity.class)
                        .putExtra(ExtraConstant.NewPropImgList, newPropImgBos)
                        .putExtra(ExtraConstant.IMG_POS, position));
            }
        });
        specialLoadView.setLoadStatusListener(new AbstractSpecialLoadView.LoadStatusListener() {
            @Override
            public void load() {
                mainRequest();
            }
        });
        consultView.initRequestBuilder(GlideLoad.initRound(this), new StaffItemDetailOnClick() {
            @Override
            public void onClick(final StaffDo staffDo, int tag, String imContent, String msgContent) {
                switch (tag) {
                    case 1:
                        startActivity(new Intent(NewEstDetailActivity.this, ChatActivity.class)
                                .putExtra(ExtraConstant.TargetId, RongUserIdUtil.getSatffId(staffDo.getStaffNo()))
                                .putExtra(ExtraConstant.MessageTarget, 3)
                                .putExtra(ExtraConstant.MessageTargetValue, newEstId)
                                .putExtra(ExtraConstant.MessageCome, imContent));
                        baiduEvent("D3_3_Click");
                        break;
                    case 2:
                        ContactUtil.sendMsg(NewEstDetailActivity.this, staffDo.getMobile(), msgContent);
                        baiduEvent("D3_4_Click");
                        break;
                    case 3:
                        new AlertDialog.Builder(NewEstDetailActivity.this)
                                .setMessage(String.format(Locale.CHINA, "拨打:%s,%s",
                                        staffDo.getBigCode(), staffDo.getExtCode()))
                                .setPositiveButton("拨打", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        ContactUtil.dial(NewEstDetailActivity.this, staffDo.getBigCode(), staffDo.getExtCode());
                                        baiduEvent("D3_2_Click");
                                    }
                                }).setNegativeButton("取消", null)
                                .create()
                                .show();
                        break;
                    default:
                        break;
                }
                if (tag != 0) {
                    RxDataBase.saveStaff(staffDo)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .compose(NewEstDetailActivity.this.<Void>bindUntilEvent(ActivityEvent.DESTROY))
                            .subscribe(new Action1<Void>() {
                                @Override
                                public void call(Void aVoid) {

                                }
                            });
                }
            }
        });
        bottomSheetBehavior = BottomSheetBehavior.from(consultView);
        bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                overView.setAlpha(slideOffset);
                overView.setVisibility(slideOffset > 0 ? View.VISIBLE : View.GONE);
            }
        });
        locationClient = MyLocation.getLocationClient();
        RxMap.location(locationClient, false)
                .compose(this.<BDLocation>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<BDLocation>() {
                    @Override
                    public void call(BDLocation bdLocation) {
                        cancelLoadingDialog();
                        switch (bdLocation.getLocType()) {
                            case 61:
                            case 161:
                                NaviParaOption naviParaOption = new NaviParaOption();
                                naviParaOption.startPoint(new LatLng(bdLocation.getLatitude(), bdLocation
                                        .getLongitude()))
                                        .endPoint(new LatLng(newPropExtInfoBo.getBaseNewPropBo().getLat(),
                                                newPropExtInfoBo.getBaseNewPropBo().getLng()));
                                BaiduMapNavigation.openBaiduMapNavi(naviParaOption, NewEstDetailActivity.this);
                                break;
                            default:
                                snack("定位失败");
                                break;
                        }
                    }
                });
        atv_nav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocation();
            }
        });
        atv_share.setOnClickListener(this);

        newEstId = getIntent().getStringExtra(ExtraConstant.NewEstId);
        bizUnit();
        mainRequest();
    }

    /**
     * 主体信息请求
     */
    private void mainRequest() {
        new NewPropExtInfoApi(newEstId, NewEstDetailActivity.class, NewPropExtInfoRo.class, new
                IResponseListener<NewPropExtInfoRo>() {
                    @Override
                    public void onResponse(NewPropExtInfoRo newPropExtInfoRo) {
                        specialLoadView.loadSuccess();
                        prl_tool.setVisibility(View.VISIBLE);
                        newPropExtInfoBo = newPropExtInfoRo.getNewPropExtInfoBo();
                        setData();
                        otherRequest();
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        specialLoadView.loadError();
                    }
                }).startRequest();
    }

    /**
     * 其他信息请求
     */
    private void otherRequest() {
        /*大图*/
        new NewPropImgApi(NewEstDetailActivity.class, NewPropImgRo.class, "EstImgs", newEstId, new
                IResponseListener<NewPropImgRo>() {
                    @Override
                    public void onResponse(NewPropImgRo newPropImgRo) {
                        final ArrayList<NewPropImgBo> temp = newPropImgRo.getNewPropImgBos();
                        if (newPropImg == null ||
                                temp == null ||
                                temp.size() == 0)
                            return;
                        newPropImgBos.clear();
                        newPropImgBos.addAll(temp);
                        bigImgList.clear();
                        for (NewPropImgBo newPropImgBo : newPropImgBos) {
                            String imgAddressThumb = newPropImgBo.getFileUrl();
                            imgAddressThumb = imgAddressThumb == null || !imgAddressThumb.contains(".") ? "" :
                                    String.format(Locale.CHINA,
                                            "%s%s",
                                            newPropImg,
                                            imgAddressThumb.replace(".",
                                                    String.format(Locale.CHINA, "_%dx%d_f.", newPropImgBo.getWidth()
                                                            * 50 /
                                                            100, newPropImgBo.getHeight() * 50 / 100)));
                            bigImgList.add(imgAddressThumb);
                        }
                        newEstDetailImgLayout.setImgList(bigImgList);
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }).startRequest();

        /*户型图*/
        new NewPropImgApi(NewEstDetailActivity.class, NewPropImgRo.class, "HouseTypeImgs", newEstId, 1, new
                IResponseListener<NewPropImgRo>() {
                    @Override
                    public void onResponse(NewPropImgRo newPropImgRo) {
                        final ArrayList<NewPropImgBo> temp = newPropImgRo.getNewPropImgBos();
                        if (temp == null ||
                                temp.size() == 0)
                            return;
                        houseTypeImgBos.clear();
                        houseTypeImgBos.addAll(temp);
                        houseTypeImgList.clear();
                        for (NewPropImgBo newPropImgBo : houseTypeImgBos) {
                            String imgAddressThumb = newPropImgBo.getFileUrl();
                            imgAddressThumb = imgAddressThumb == null || !imgAddressThumb.contains(".") ? "" :
                                    String.format(Locale.CHINA,
                                            "%s%s",
                                            newPropImg,
                                            imgAddressThumb.replace(".",
                                                    String.format(Locale.CHINA, "_%dx%d_f.", newPropImgBo.getWidth()
                                                            * 50 /
                                                            100, newPropImgBo.getHeight() * 50 / 100)));
                            bigImgList.add(imgAddressThumb);
                            houseTypeImgList.add(imgAddressThumb);
                        }
                        if (vs_house_type != null) {
                            vs_house_type.inflate();
                            AppCompatTextView atv_house_type_num = (AppCompatTextView) findViewById(R.id
                                    .atv_house_type_num);
                            NewEstHouseTypeView newEstHouseTypeView = (NewEstHouseTypeView) findViewById(R.id
                                    .newEstHouseTypeView);
                            if (atv_house_type_num != null) {
                                atv_house_type_num.setText(String.format(Locale.CHINA, "(%d)", houseTypeImgBos.size()));
                            }
                            if (newEstHouseTypeView != null) {
                                newEstHouseTypeView.initRequestBuilder(requestBuilder);
                                newEstHouseTypeView.setRecyclerViewItemOnClickListener(
                                        new RecyclerViewItemOnClickListener<Integer>() {
                                            @Override
                                            public void onItemOnClick(Integer integer, int tag) {
                                                //户型图
                                                startActivity(new Intent(NewEstDetailActivity.this,
                                                        NewEstHouseTypeActivity
                                                                .class)
                                                        .putExtra(ExtraConstant.IMG_POS, integer)
                                                        .putExtra(ExtraConstant.Price, newPropExtInfoBo
                                                                .getAveragePrice())
                                                        .putExtra(ExtraConstant.NewPropImgList, houseTypeImgBos));
                                            }
                                        });
                                newEstHouseTypeView.setList(houseTypeImgBos, houseTypeImgList);
                            }
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }).startRequest();

        /*活动*/
        NewEstActListApi newEstActListApi = new NewEstActListApi(NewEstDetailActivity.class, NewEstActListRo.class,
                new IResponseListener<NewEstActListRo>() {
                    @Override
                    public void onResponse(NewEstActListRo newEstActListRo) {
                        final ArrayList<NewEstActDo> temp = newEstActListRo.getList();
                        if (temp == null || temp.size() == 0)
                            return;
                        newEstActDos.clear();
                        newEstActDos.addAll(temp);
                        if (vs_activity != null) {
                            vs_activity.inflate();
                            final NewEstActDo newEstActDo = newEstActDos.get(0);
                            final RelativeLayout rl_act = (RelativeLayout) findViewById(R.id.rl_act);
                            AppCompatTextView atv_new_est_act_desc = (AppCompatTextView) findViewById(R.id
                                    .atv_new_est_act_desc);
                            AppCompatTextView atv_new_est_act_book_num = (AppCompatTextView) findViewById(R.id
                                    .atv_new_est_act_book_num);
                            AppCompatTextView atv_new_est_act_date = (AppCompatTextView) findViewById(R.id
                                    .atv_new_est_act_date);
                            if (rl_act != null) {
                                rl_act.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        startActivity(new Intent(NewEstDetailActivity.this, NewEstActDetailActivity
                                                .class)
                                                .putExtra(ExtraConstant.NewEstActId, newEstActDo.getActId()));
                                    }
                                });
                            }
                            if (atv_new_est_act_desc != null) {
                                atv_new_est_act_desc.setText(newEstActDo.getDescription());
                            }
                            if (atv_new_est_act_book_num != null) {
                                atv_new_est_act_book_num.setText(String.valueOf(newEstActDo.getShowBookCnt()));
                            }
                            if (atv_new_est_act_date != null) {
                                atv_new_est_act_date.setText(Html.fromHtml(DateUtil.getRemainTime(newEstActDo
                                        .getEndDate())));
                            }
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        newEstActListApi.setEstExtId(newEstId);
        newEstActListApi.startRequest();

        /*周边新盘*/
        if (newPropExtInfoBo != null &&
                newPropExtInfoBo.getBaseNewPropBo() != null &&
                newPropExtInfoBo.getBaseNewPropBo().getLat() != 0 &&
                newPropExtInfoBo.getBaseNewPropBo().getLng() != 0) {
            NewEstListApi newEstListApi = new NewEstListApi(NewEstDetailActivity.class, NewEstListRo.class, new
                    IResponseListener<NewEstListRo>() {
                        @Override
                        public void onResponse(NewEstListRo newEstListRo) {
                            final ArrayList<NewEstDo> temp = newEstListRo.getNewEstDoArrayList();
                            if (temp == null ||
                                    temp.size() == 0 ||
                                    temp.size() == 1)
                                return;
                            newEstDos.clear();
                            newEstDos.addAll(temp);
                            if (vs_around_new_est != null) {
                                vs_around_new_est.inflate();
                                final NewEstDo newEstDo1 = newEstDos.get(1);
                                ImageView img_around_est1 = (ImageView) findViewById(R.id.img_around_est1);
                                AppCompatTextView atv_around_est_price1 = (AppCompatTextView) findViewById(R.id
                                        .atv_around_est_price1);
                                AppCompatTextView atv_around_est_title1 = (AppCompatTextView) findViewById(R.id
                                        .atv_around_est_title1);
                                String imgAddr = newEstDo1.getIconUrl();
                                imgAddr = imgAddr == null || !imgAddr.contains(".") ? "" : imgAddr.replace(".",
                                        "_640x200_f.");
                                GlideLoad.load(new GlideLoad.Builder(requestBuilder, String.format(Locale.CHINA, "%s%s",
                                        newPropImg, imgAddr))
                                        .placeHolder(R.drawable.ic_centa_square_logo)
                                        .error(R.drawable.ic_centa_square_logo)
                                        .openWifiSwitch()
                                        .into(img_around_est1));
                                if (atv_around_est_price1 != null) {
                                    atv_around_est_price1.setText(PriceUtil.newEstAvgPrice(newEstDo1.getAveragePrice
                                            ()));
                                }
                                if (atv_around_est_title1 != null) {
                                    atv_around_est_title1.setText(newEstDo1.getEstName());
                                }
                                if (newEstDos.size() > 2) {
                                    final NewEstDo newEstDo2 = newEstDos.get(2);
                                    FrameLayout fl_around_est2 = (FrameLayout) findViewById(R.id.fl_around_est2);
                                    if (fl_around_est2 != null) {
                                        fl_around_est2.setVisibility(View.VISIBLE);
                                    }
                                    ImageView img_around_est2 = (ImageView) findViewById(R.id.img_around_est2);
                                    AppCompatTextView atv_around_est_price2 = (AppCompatTextView) findViewById(R.id
                                            .atv_around_est_price2);
                                    AppCompatTextView atv_around_est_title2 = (AppCompatTextView) findViewById(R.id
                                            .atv_around_est_title2);
                                    imgAddr = newEstDo2.getIconUrl();
                                    imgAddr = imgAddr == null || !imgAddr.contains(".") ? "" : imgAddr.replace(".",
                                            "_640x200_f.");
                                    GlideLoad.load(new GlideLoad.Builder(requestBuilder, String.format(Locale.CHINA,
                                            "%s%s",
                                            newPropImg, imgAddr))
                                            .placeHolder(R.drawable.ic_centa_square_logo)
                                            .error(R.drawable.ic_centa_square_logo)
                                            .openWifiSwitch()
                                            .into(img_around_est2));
                                    if (atv_around_est_price2 != null) {
                                        atv_around_est_price2.setText(PriceUtil.newEstAvgPrice(newEstDo2
                                                .getAveragePrice()));
                                    }
                                    if (atv_around_est_title2 != null) {
                                        atv_around_est_title2.setText(newEstDo2.getEstName());
                                    }
                                }
                            }
                        }

                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    });
            newEstListApi.setLength(3);
            LatLng estLatLng = (new LatLng(newPropExtInfoBo.getBaseNewPropBo().getLat(),
                    newPropExtInfoBo.getBaseNewPropBo().getLng()));
            newEstListApi.setLatLng(estLatLng);
            newEstListApi.setSortBy("2");
            newEstListApi.startRequest();
        }

        /*周边小区*/
        if (saleEnable &&
                newPropExtInfoBo != null &&
                newPropExtInfoBo.getBaseNewPropBo() != null &&
                newPropExtInfoBo.getBaseNewPropBo().getLat() != 0 &&
                newPropExtInfoBo.getBaseNewPropBo().getLng() != 0) {
            EsfEstateListApi esfEstateListApi = new EsfEstateListApi(NewEstDetailActivity.class, EsfEstateListRo
                    .class, new IResponseListener<EsfEstateListRo>() {
                @Override
                public void onResponse(EsfEstateListRo esfEstateListRo) {
                    final ArrayList<EsfEstateDo> temp = esfEstateListRo.getList();
                    if (temp == null ||
                            temp.size() == 0)
                        return;
                    esfEstateDos.clear();
                    esfEstateDos.addAll(temp);
                    if (vs_around_esf != null) {
                        vs_around_esf.inflate();
                        final EsfEstateDo esfEstateDo1 = esfEstateDos.get(0);
                        ImageView img_around_esf1 = (ImageView) findViewById(R.id.img_around_esf1);
                        AppCompatTextView atv_around_esf_price1 = (AppCompatTextView) findViewById(R.id
                                .atv_around_esf_price1);
                        AppCompatTextView atv_around_esf_title1 = (AppCompatTextView) findViewById(R.id
                                .atv_around_esf_title1);
                        GlideLoad.load(new GlideLoad.Builder(requestBuilder, esfEstateDo1.getDefaultImg())
                                .placeHolder(R.drawable.ic_centa_square_logo)
                                .error(R.drawable.ic_centa_square_logo)
                                .openWifiSwitch()
                                .into(img_around_esf1));
                        if (atv_around_esf_price1 != null) {
                            atv_around_esf_price1.setText(PriceUtil.esfSaleAvgPrice(esfEstateDo1.getCestAvgPrice()));
                        }
                        if (atv_around_esf_title1 != null) {
                            atv_around_esf_title1.setText(esfEstateDo1.getName());
                        }
                        if (esfEstateDos.size() > 1) {
                            final EsfEstateDo esfEstateDo2 = esfEstateDos.get(1);
                            FrameLayout fl_around_esf2 = (FrameLayout) findViewById(R.id.fl_around_esf2);
                            if (fl_around_esf2 != null) {
                                fl_around_esf2.setVisibility(View.VISIBLE);
                            }
                            ImageView img_around_esf2 = (ImageView) findViewById(R.id.img_around_esf2);
                            AppCompatTextView atv_around_esf_price2 = (AppCompatTextView) findViewById(R.id
                                    .atv_around_esf_price2);
                            AppCompatTextView atv_around_esf_title2 = (AppCompatTextView) findViewById(R.id
                                    .atv_around_esf_title2);
                            GlideLoad.load(new GlideLoad.Builder(requestBuilder, esfEstateDo2.getDefaultImg())
                                    .placeHolder(R.drawable.ic_centa_square_logo)
                                    .error(R.drawable.ic_centa_square_logo)
                                    .openWifiSwitch()
                                    .into(img_around_esf2));
                            if (atv_around_esf_price2 != null) {
                                atv_around_esf_price2.setText(PriceUtil.esfSaleAvgPrice(esfEstateDo2.getCestAvgPrice
                                        ()));
                            }
                            if (atv_around_esf_title2 != null) {
                                atv_around_esf_title2.setText(esfEstateDo2.getName());
                            }
                        }
                    }
                }

                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
            LatLng estLatLng = (new LatLng(newPropExtInfoBo.getBaseNewPropBo().getLat(),
                    newPropExtInfoBo.getBaseNewPropBo().getLng()));
            esfEstateListApi.setMin(String.format(Locale.CHINA, "%.0f", newPropExtInfoBo.getAveragePrice() * 0.9));
            esfEstateListApi.setMax(String.format(Locale.CHINA, "%.0f", newPropExtInfoBo.getAveragePrice() * 1.1));
            esfEstateListApi.setType("F");
            esfEstateListApi.setRound("100000");
            esfEstateListApi.setLatLng(estLatLng);
            esfEstateListApi.setPageCount(2);
            esfEstateListApi.startRequest();
        }

        /*经纪人咨询*/
        NewPropStaffApi newPropStaffApi = new NewPropStaffApi(NewEstDetailActivity.class, NewPropStaffListRo.class,
                new IResponseListener<NewPropStaffListRo>() {
                    @Override
                    public void onResponse(NewPropStaffListRo newPropStaffListRo) {
                        final ArrayList<NewPropStaffBo> temp = newPropStaffListRo.getNewPropStaffBos();
                        if (temp != null && temp.size() > 0) {
                            newPropStaffBos.addAll(temp);
                            final StringBuilder staffSB = new StringBuilder();
                            for (NewPropStaffBo newPropStaffBo : newPropStaffBos) {
                                staffSB.append(newPropStaffBo.getStaffNo())
                                        .append(",");
                            }
                            staffSB.deleteCharAt(staffSB.length() - 1);
                            newPropPhoneApi.setStaffNos(staffSB.toString());
                            newPropPhoneApi.startRequest();
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        newPropStaffApi.setEstExtId(newEstId);
        newPropStaffApi.startRequest();

        /*新盘400号码*/
        newPropPhoneApi = new NewPropPhoneApi(NewEstDetailActivity.class, NewPropPhoneRo.class, new
                IResponseListener<NewPropPhoneRo>() {
                    @Override
                    public void onResponse(NewPropPhoneRo newPropPhoneRo) {
                        final ArrayList<NewPropPhoneBo> newPropPhoneBos = newPropPhoneRo.getNewPropPhoneBos();
                        if (newPropPhoneBos == null ||
                                newPropPhoneBos.size() == 0)
                            return;
                        ArrayList<StaffDo> staffDos = new ArrayList<>();
                        for (int i = 0; i < newPropStaffBos.size(); i++) {
                            NewPropStaffBo newPropStaffBo = newPropStaffBos.get(i);
                            StaffDo staffDo = new StaffDo();
                            staffDo.setCityCode(newPropStaffBo.getCityCode());
                            staffDo.setStaffNo(newPropStaffBo.getStaffNo());
                            staffDo.setCnName(newPropStaffBo.getCnName());
                            staffDo.setMobile(newPropStaffBo.getMobile());
                            staffDo.setBigCode(newPropPhoneBos.get(i).getBigCode());
                            staffDo.setExtCode(newPropPhoneBos.get(i).getExtCode());
                            staffDo.setImgUrl(String.format(Locale.CHINA, "%s%s.jpg", AppConstant.AgentPhoto,
                                    newPropStaffBo
                                            .getStaffNo()));
                            staffDos.add(staffDo);
                        }
                        consultView.setNewEst(newPropExtInfoBo);
                        consultView.setStaffs(staffDos);
                        btn_consult.setEnabled(true);
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        newPropPhoneApi.setTargetValue(newEstId);
        collectStatus();
    }

    /**
     * 设置数据
     */
    private void setData() {
        final BaseNewPropBo baseNewPropBo = newPropExtInfoBo.getBaseNewPropBo();
        newEstDetailImgLayout.setTitleAndType(newPropExtInfoBo.getAdName(), newPropExtInfoBo.getEstType());
        atv_price.setText(PriceUtil.newEstAvgPrice(newPropExtInfoBo.getAveragePrice()));
        atv_status.setText(("认购".equals(newPropExtInfoBo.getBaseNewPropBo().getStatus()) || "持销".equals(newPropExtInfoBo
                .getBaseNewPropBo().getStatus()) || "尾盘".equals(newPropExtInfoBo.getBaseNewPropBo().getStatus())) ? "在售" : "待售");
        TextFormatUtil.setNewEstOpen(atv_open, newPropExtInfoBo.getOpDate());
        TextFormatUtil.setNewEstOpen(atv_live, newPropExtInfoBo.getLiveDate());
        TextFormatUtil.setText(atv_feature, newPropExtInfoBo.getFeatures());
        TextFormatUtil.setText(atv_fitment, baseNewPropBo.getFitment());
        TextFormatUtil.setText(atv_property_right, newPropExtInfoBo.getPropertyRight() == 0 ?
                "暂无" : String.format(Locale.CHINA, "%d年", newPropExtInfoBo.getPropertyRight()));
        TextFormatUtil.setText(atv_mgt_price, PriceUtil.mgtPrice(newPropExtInfoBo.getMgtPrice()));
        TextFormatUtil.setText(atv_mgt_company, baseNewPropBo.getMgtCompany());
        TextFormatUtil.setText(atv_developer, baseNewPropBo.getDeveloper());

        if (vs_new_est_traffic != null &&
                !TextUtils.isEmpty(baseNewPropBo.getTraffic())) {
            vs_new_est_traffic.inflate();
            atv_traffic = (AppCompatTextView) findViewById(R.id.atv_traffic);
            arrow_traffic = (ImageView) findViewById(R.id.img_arrow_traffic);
            atv_traffic.setText(baseNewPropBo.getTraffic());
            atv_traffic.post(new Runnable() {
                @Override
                public void run() {
                    if (atv_traffic.getLineCount() < 3) {
                        atv_traffic.setMaxLines(atv_traffic.getLineCount());
                        arrow_traffic.setVisibility(View.INVISIBLE);
                    }
                }
            });
        }
        if (vs_new_est_support != null &&
                !TextUtils.isEmpty(baseNewPropBo.getProjectSupporting())) {
            vs_new_est_support.inflate();
            atv_support = (AppCompatTextView) findViewById(R.id.atv_support);
            arrow_support = (ImageView) findViewById(R.id.img_arrow_support);
            atv_support.setText(baseNewPropBo.getProjectSupporting());
            atv_support.post(new Runnable() {
                @Override
                public void run() {
                    if (atv_support.getLineCount() < 3) {
                        atv_support.setMaxLines(atv_support.getLineCount());
                        arrow_support.setVisibility(View.INVISIBLE);
                    }
                }
            });
        }
        atv_address.setText(String.format(Locale.CHINA, "%s-%s %s",
                baseNewPropBo.getNewEstDistrictBo() == null ? "暂无" : baseNewPropBo.getNewEstDistrictBo()
                        .getGScopeCnName(),
                baseNewPropBo.getNewEstGScopeBo() == null ? "暂无" : baseNewPropBo.getNewEstGScopeBo().getGScopeCnName(),
                baseNewPropBo.getAddress()));
        atv_map_name.setText(newPropExtInfoBo.getAdName());
        if (baseNewPropBo.getLat() != 0 &&
                baseNewPropBo.getLng() != 0) {
            img_arrow_address.setVisibility(View.VISIBLE);
            atv_nav.setVisibility(View.VISIBLE);
            rl_map.setVisibility(View.VISIBLE);
            GlideLoad.load(new GlideLoad.Builder(requestBuilder,
                    BdMapUtil.getBaiduMapImgUrl(baseNewPropBo.getLng(), baseNewPropBo.getLat()))
                    .placeHolder(R.drawable.ic_banner)
                    .error(R.drawable.ic_banner)
                    .openWifiSwitch()
                    .into(img_map));
        }
        NewEstDo newEstDo = new NewEstDo();
        newEstDo.setEstExtId(newEstId);
        newEstDo.setOnline(newPropExtInfoBo.isOnline());
        newEstDo.setTop(newPropExtInfoBo.isTop());
        newEstDo.setAdName(newPropExtInfoBo.getAdName());
        newEstDo.setEstType(newPropExtInfoBo.getEstType());
        newEstDo.setAveragePrice(newPropExtInfoBo.getAveragePrice());
        newEstDo.setMinUnitPrice(newPropExtInfoBo.getMinUnitPrice());
        newEstDo.setMaxUnitPrice(newPropExtInfoBo.getMaxUnitPrice());
        newEstDo.setMinTotalPrice(newPropExtInfoBo.getMinTotalPrice());
        newEstDo.setMaxTotalPrice(newPropExtInfoBo.getMaxTotalPrice());
        newEstDo.setAddress(baseNewPropBo.getAddress());
        newEstDo.setLat(baseNewPropBo.getLat());
        newEstDo.setLng(baseNewPropBo.getLng());
        newEstDo.setStatus(baseNewPropBo.getStatus());
        newEstDo.setFitment(baseNewPropBo.getFitment());
        newEstDo.setIconUrl(newPropExtInfoBo.getIconUrl());
        newEstDo.setRegionName(baseNewPropBo.getNewEstDistrictBo() == null ? "暂无" :
                baseNewPropBo.getNewEstDistrictBo().getGScopeCnName());
        newEstDo.setGscopName(baseNewPropBo.getNewEstGScopeBo() == null ? "暂无" :
                baseNewPropBo.getNewEstGScopeBo().getGScopeCnName());
        newEstDo.setEstName(baseNewPropBo.getEstName());

        RxDataBase.fpHistorySave(3, newEstId, newEstDo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<Void>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {

                    }
                });
    }

    /**
     * 开始定位
     */
    private void startLocation() {
        showLoadingDialog();
        locationClient.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_traffic:
                if (atv_traffic.getLineCount() > 2) {
                    atv_traffic.setMaxLines(expandTraffic ? 3 : 30);
                    arrow_traffic.setRotationX(expandTraffic ? 0f : 180f);
                    expandTraffic = !expandTraffic;
                }
                break;
            case R.id.rl_support:
                if (atv_support.getLineCount() > 2) {
                    atv_support.setMaxLines(expandSupport ? 3 : 30);
                    arrow_support.setRotationX(expandSupport ? 0f : 180f);
                    expandSupport = !expandSupport;
                }
                break;
            case R.id.rl_base_info:
                //更多楼盘资料
                if (newPropExtInfoBo != null) {
                    startActivity(new Intent(this, NewEstInfoActivity.class)
                            .putExtra(ExtraConstant.NewEstInfo, newPropExtInfoBo));
                }
                break;
            case R.id.rl_address://地图
            case R.id.img_map://地图
                if (newPropExtInfoBo.getBaseNewPropBo() != null) {
                    if (newPropExtInfoBo.getBaseNewPropBo().getLat() == 0 || newPropExtInfoBo.getBaseNewPropBo()
                            .getLng() == 0) {
                        snack("地理位置获取失败");
                    } else {
                        startActivity(new Intent(this, AroundMapActivity.class)
                                .putExtra(ExtraConstant.LatLng, new LatLng(newPropExtInfoBo.getBaseNewPropBo().getLat(),
                                        newPropExtInfoBo.getBaseNewPropBo().getLng()))
                                .putExtra(ExtraConstant.MAP_NAME, newPropExtInfoBo.getAdName()));
                    }
                }
                break;
            case R.id.fl_around_est1:
                //周边新盘1
                if (newEstDos.size() > 1) {
                    startActivity(new Intent(this, NewEstDetailActivity.class)
                            .putExtra(ExtraConstant.NewEstId, newEstDos.get(1).getEstExtId()));
                }
                break;
            case R.id.fl_around_est2:
                //周边新盘2
                if (newEstDos.size() > 2) {
                    startActivity(new Intent(this, NewEstDetailActivity.class)
                            .putExtra(ExtraConstant.NewEstId, newEstDos.get(2).getEstExtId()));
                }
                break;
            case R.id.fl_around_esf1:
                //周边小区1
                if (esfEstateDos.size() > 0) {
                    startActivity(new Intent(this, EsfEstateDetailActivity.class)
                            .putExtra(ExtraConstant.CestCode, esfEstateDos.get(0).getCestCode()));
                }
                break;
            case R.id.fl_around_esf2:
                //周边小区1
                if (esfEstateDos.size() > 1) {
                    startActivity(new Intent(this, EsfEstateDetailActivity.class)
                            .putExtra(ExtraConstant.CestCode, esfEstateDos.get(1).getCestCode()));
                }
                break;
            case R.id.btn_consult:
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                break;
            case R.id.overView:
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                break;
            case R.id.collectView:
                collect();
                break;
            case R.id.atv_share://分享
                if (!TextUtils.isEmpty(shareUrl)) {
                    if (shareDialog == null) {
                        ShareBo shareBo = new ShareBo(3);
                        shareBo.setHouseName(newPropExtInfoBo.getAdName());
                        shareBo.setRegionGscop(String.format(Locale.CHINA, "%s-%s",
                                newPropExtInfoBo.getBaseNewPropBo().getNewEstDistrictBo().getGScopeCnName(),
                                newPropExtInfoBo.getBaseNewPropBo().getNewEstGScopeBo().getGScopeCnName()));
                        shareBo.setAvgPrice(String.format(Locale.CHINA, "%.0f元/平", newPropExtInfoBo.getAveragePrice()));
                        shareBo.setHouseUrl(shareUrl.replace("{0}", newEstId));
                        String imgAddress = newPropExtInfoBo.getIconUrl();
                        imgAddress = imgAddress.contains(".") ? imgAddress.replace(".",
                                "_150x150_f.") : "";
                        shareBo.setImageUrl(TextUtils.isEmpty(imgAddress) ?
                                "" : String.format(Locale.CHINA, "%s%s",
                                newPropImg, imgAddress));
                        shareDialog = new ShareDialog(this, shareBo);
                    }
                    shareDialog.show();
                }
                baiduEvent("D3_1_Type");
                break;
            default:
                break;
        }
    }

    private void collect() {
        if (AppConstant.IsLogin) {
            if (collectView.isCollect()) {
                RxRequest.cancelCollect(NewEstDetailActivity.class, collectView.getCollectId())
                        .compose(this.<SimpleUserCenterRo>bindUntilEvent(ActivityEvent.DESTROY))
                        .subscribe(new Action1<SimpleUserCenterRo>() {
                            @Override
                            public void call(SimpleUserCenterRo simpleUserCenterRo) {
                                if (0 == simpleUserCenterRo.getResultNo()) {
                                    collectView.setCollect(false);
                                    EventBus.getDefault().post(new MineInfoUpdate(14));
                                    snack(R.string.collect_cancel);
                                } else {
                                    snack(simpleUserCenterRo.getMessage());
                                }
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                netWorkUnable();
                            }
                        });
            } else {
                RxRequest.addCollect(NewEstDetailActivity.class, AppNameType.NEWPROP, SourceType.LOUPAN, collectView
                                .getCollectId(), newEstId,
                        String.format(Locale.CHINA, "%s%s?EstExtId=%s", AppConstant.NewEstUrl,
                                "NewPropExtInfoRequest", newEstId))
                        .compose(this.<SimpleUserCenterRo>bindUntilEvent(ActivityEvent.DESTROY))
                        .subscribe(new Action1<SimpleUserCenterRo>() {
                            @Override
                            public void call(SimpleUserCenterRo simpleUserCenterRo) {
                                if (0 == simpleUserCenterRo.getResultNo()) {
                                    collectView.setCollect(true);
                                    if (0 != simpleUserCenterRo.getResult()) {
                                        collectView.setCollectId(String.valueOf(simpleUserCenterRo.getResult()));
                                    }
                                    EventBus.getDefault().post(new MineInfoUpdate(14));
                                    SprfUtil.setInt(NewEstDetailActivity.this,
                                            String.format("%s_%s", SprfConstant.COLLECT_POSITION, AppConstant
                                                    .CityCode), 14);
                                    snack(R.string.collect_success);
                                } else {
                                    snack(simpleUserCenterRo.getMessage());
                                    collectStatus();
                                }
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                netWorkUnable();
                            }
                        });
            }
        } else {
            startActivityForResult(new Intent(this, LoginActivity.class), CommonConstant.REQ_COLLECT);
        }
    }

    /**
     * 收藏状态
     */
    private void collectStatus() {
        if (AppConstant.IsLogin) {
            RxRequest.collectStatus(NewEstDetailActivity.class, newEstId,
                    String.format(Locale.CHINA, "%s%s?EstExtId=%s", AppConstant.NewEstUrl, "NewPropExtInfoRequest",
                            newEstId))
                    .compose(this.<CollectInfoListRo>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<CollectInfoListRo>() {
                        @Override
                        public void call(CollectInfoListRo collectInfoListRo) {
                            final ArrayList<CollectInfoBo> temp = collectInfoListRo.getList();
                            if (temp != null &&
                                    temp.size() > 0) {
                                collectView.setCollectId(String.valueOf(temp.get(0).getCollectID()));
                                collectView.setCollect(!temp.get(0).isDel());
                            } else {
                                collectView.setCollect(false);
                            }
                        }
                    });
        }
    }

    /**
     * 获取配置信息
     */
    private void bizUnit() {
        RxDataBase.getBizUnit()
                .compose(this.<BizUnitDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BizUnitDo>() {
                    @Override
                    public void call(BizUnitDo bizUnitDo) {
                        shareUrl = bizUnitDo.getShareXingfang();
                        newPropImg = bizUnitDo.getNewpropimg();
                        saleEnable = bizUnitDo.isEnableErshoufang();
                        consultView.setImEnable(bizUnitDo.isShowTalk());
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CommonConstant.REQ_COLLECT:
                    collect();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK &&
                bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
